# coding: utf-8
import logging
import os
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler


class Log(object):
    app = None
    _config = None

    def __init__(self, log_name=None):
        self.logger = logging.getLogger(log_name)

    def init_app(self, app):
        if not app:
            raise Exception("参数app无效")
        self.app = app
        self.app.log = self
        self._config = self.app.config.copy()
        return self.setup()

    def from_object(self, obj):
        if self._config is not None:
            return
        config = dict()
        for key in dir(obj):
            if key.isupper():
                config[key] = getattr(obj, key)
        config = self._set_default(config)
        self._config = config
        self.setup()

    def setup(self):
        config = self._set_default(self._config)

        # 1.日志器
        logger = logging.getLogger(config.get("LOG_NAME"))
        logger.setLevel(config.get("LOG_LEVEL"))

        formatter = logging.Formatter('%(name)s: %(levelname)s %(asctime)s %(filename)s:%(lineno)d %(message)s')

        file = config["LOG_FILENAME"].split(".")[0]
        filename = os.path.join(os.path.abspath(os.curdir), "logs", "{file}.all.log".format(file=file))
        # filename = os.path.dirname(self.app.root_path) + "\\logs\\" + file + ".all.log"
        path = os.path.dirname(filename)
        if not os.path.exists(path):
            os.mkdir(path)
        file_handler = TimedRotatingFileHandler(filename, when="D", backupCount=config.get("LOG_BACKUP_COUNT"))
        file_handler.setFormatter(formatter)

        # 错误日志
        filename = os.path.join(os.path.abspath(os.curdir), "logs", "{file}.error.log".format(file=file))
        error_file = RotatingFileHandler(
            filename,
            maxBytes=config.get("LOG_MAX_BYTES"),
            backupCount=config.get("LOG_BACKUP_COUNT")
        )
        error_file.setLevel("ERROR")
        error_file.setFormatter(formatter)

        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)

        logger.addHandler(file_handler)
        logger.addHandler(error_file)
        logger.addHandler(console_handler)
        self.logger = logger
        return logger

    @staticmethod
    def _set_default(config):
        config.setdefault('LOG_LEVEL', "DEBUG")
        config.setdefault('LOG_FILENAME', "logs\\log.log")
        config.setdefault('LOG_MAX_BYTES', 1024 * 1024 * 100)
        config.setdefault('LOG_BACKUP_COUNT', 5)  # 最多备份5个
        config.setdefault('LOG_NAME', None)
        return config
